package javabasics.nio;

import java.io.*;
import java.nio.channels.FileChannel;

/**
 * @Author suxiaoxiao
 * @Date 2019/6/13 23:30
 * @Version 1.0
 */
public class Stream {

    /**
     * 写：236 ms
     * 读：202 ms
     * @param args
     */
    public static void main(String[] args) {
        int numOfInts = 4000000;

//        Long startTime = System.currentTimeMillis();
//        streamWriteFile(numOfInts);
//        System.out.println("Stream写耗时：" + (System.currentTimeMillis() - startTime));

        Long startTime = System.currentTimeMillis();
        streamReadFile(numOfInts);
        System.out.println("Stream读耗时：" + (System.currentTimeMillis() - startTime));
    }

    public static void streamWriteFile (int numOfInts) {

        try (DataOutputStream dataOutputStream =
                     new DataOutputStream(
                             new BufferedOutputStream(
                                     new FileOutputStream(
                                             new File("d:\\temp_stream.tmp"))))) {
            for (int i = 0; i < numOfInts; i++) {
                dataOutputStream.writeInt(i);
            }
        } catch (FileNotFoundException e) {
            System.out.println("文件没找到");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("IO传输异常");
        }
    }

    public static void streamReadFile (int numOfInts) {
        try (DataInputStream dis =
                     new DataInputStream(
                             new BufferedInputStream(
                                     new FileInputStream(
                                             new File("d:\\temp_stream.tmp"))))) {
            for (int i = 0; i < numOfInts; i++) {
                dis.readInt();
            }
        } catch (FileNotFoundException e) {
            System.out.println("文件没找到");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("IO传输异常");
        }
    }

}
